<template>
  <div class="app-container">
    <my-tree-selector-query
      ref="regionTree"
      title="部署区域"
      :current-node-key="this.filter.data.regionId"
      :default-expanded-keys="[this.filter.data.regionId]"
      :options="regionDataOptions"
      :treeProps="{ children: 'children',label: 'name'}"
      @click-node="handleNodeClick"
    />
    <div class="right-wrap">
      <u-page-config
        :filter-array="filterArray"
        v-model="filter"
        label-width="80px"
        :getList="getList"
        :actionBtn="actionBtn"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="total"
        :loading="loading"
        showSelection
        @export="handleExport"
        @handleSelectionChange="handleSelectionChange"
      >
        <template #groupId="{item}">
          <treeselect
            v-model="filter.data.groupId"
            :options="groupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择分组"
            style="width: 240px"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </template>
         <template #network="{item}">
          <treeselect
                v-model="filter.data.branchCode"
                :options="branchDataOptions"
                :normalizer="branchNormalizer"
                placeholder="选择设备部署默认网点"
                style="width: 240px"
                noOptionsText="暂无选项"
                noResultsText="没有匹配的搜索结果"
              />
        </template>
      </u-page-config>
    </div>


  </div>
</template>

<script>
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
import table from "@/mixin/uTable";
import UPageConfig from "@/components/uPageConfig/index";
import Treeselect from "@riophae/vue-treeselect";
import {listStatistics} from "@/api/system/statistics";
import {listGroup} from "@/api/device/group";
import {handleTree} from "@/utils/ruoyi";
import {businessTypeOptions} from '@/utils/dicts'

export default {
  name: "DeviceMonitoring",
  mixins: [table],
  dicts: ['device_status'],
  components: {
    UPageConfig,
    MyTreeSelectorQuery,
    Treeselect

  },
  data() {
    return {
      filter: {
        pageSize: 10,
        pageNum: 1,
        data: {
          businessType: undefined,
          createTime: undefined
        }
      },
      filterArray: [
        {label: "部署分组", key: "groupId", type: "slot", slot: 'groupId'},
        {label: "事项编码", key: "serviceCode", type: "input"},
        {label: "事项名称", key: "serviceName", type: "input"},
        {label: "业务类型", key: "businessType", type: "select", options: []},
        {label: "默认网点", key: "branchCode", type: "slot", slot: 'network'},
        {label: "起止日期", key: "createTime", type: "daterange", noRequestParams: true}
      ],
      actionBtn: [
        {
          type: 'warning',
          text: '导出',
          icon: 'el-icon-download',
          emit: 'export',
          size: 'small',
          permissions: 'statistics:matterClick:export'
        }
      ],
      tableColumn: [
        {label: "事项编码", prop: "serviceCode"},
        // {label: "实施部门", prop: "deptName"},
        {label: "事项名称", prop: "serviceName"},
        // {label: "分组名称", prop: "branchName"},
        {label: "业务类型", prop: "businessType", type: 'select', options: []},
        {label: "点击次数", prop: "clickSum"},
      ],
      // 分组选项
      groupOptions: [],
      remoteCommandType: '',
      // 当前勾选中的数据
      checkedDeviceList: []
    }
  },
  computed: {
    //默认显示省份ID
    provinceIdConfig() {
      return this.$store.state.app.provinceIdConfig
    },
    // 所有地区树形数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions;
    },
     // 网点树形数据
    branchDataOptions() {
      console.log(999, this.$store.state.device.branchDataOptions)
      return this.$store.state.device.branchDataOptions || []
    }
  },
  methods: {
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      const ids = this.ids;
      const params = this.getListRequestParams();
      this.download(
        "/system/statistics/export",
        params,
        `使用频率统计_${currentDate}.xlsx`,
      );
    },
    // 点击卡片自动选择筛选状态
    handleFilterDeviceStatus(deviceStatus) {
      // 清空选项
      Object.keys(this.filter.data).forEach(key => {
        if (key !== 'regionId') {
          this.filter.data[key] = undefined
        }
      })
      this.filter.data.deviceStatus = deviceStatus;
      this.getList()
    },
    remoteCommand(row, type) {
      this.setForm(row);
      this.remoteCommandType = type;
    },
    // 设置当前选择项的表单值
    setForm(row) {
      if (row && row.id) {
        this.checkedDeviceList = [row]
      } else {
        this.checkedDeviceList = this.tableData.filter((item, index) => item.id === this.ids[index]);
      }
    },
    // 下拉按钮
    handleCommand(command, row) {
      try {
        this[command](row);
      } catch (e) {
        console.log(`找不到调用的方法this.${command}`)
      }
    },
    /** 转换区域树形图数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
      /** 转换分组树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined,
      };
    },
    // 点击区域节点
    getChildrenRegion(id, options) {
      //是否还没找到，继续循环
      let going = true;
      let result = []
      let walker = (id, array) => {
        array.forEach(item => {
          if (!going) return;
          if (item['id'] === id) {
            going = false;
            result = [item];
          } else if (item['children']) {
            walker(id, item['children']);
          }
        });
      }
      walker(id, options)
      return result
    },
    /** 查询区域包含的分组管理列表 */
    getRegionGroup(regionId) {
      this.loading = true;
      listGroup({regionId}).then(res => {
        this.groupOptions = handleTree(res.rows, "id");
      }).finally(() => {
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.filter.data.regionId = data.id;
      // 清空选择的分组
      this.getRegionGroup(data.id)
      this.getList();
    },
    // 表单提交接口相关配置
    formSubmitFunConfig() {
      return {
        addFunc: () => {
        },
        modifyFunc: () => {
        },
        pk: 'id',
        options: {
          ...this.form
        },
        cbFunc: () => {
          this.visible = false
        }
      }
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    /** 查询数据列表 */
    getList() {
      // 如果点击了重置按钮，regionId被清空后，自动赋值为默认省份id
      if (!this.filter.data.regionId) {
        this.filter.data.regionId = this.provinceIdConfig;
        this.$refs.regionTree.$refs.tree.setCurrentKey(this.provinceIdConfig);
      }
      // 获取列表
      this.getInit(listStatistics, {})
    },
  },
  created() {
    // 设置默认选择区域
    this.filter.data.regionId = this.provinceIdConfig;
    // 获取分组
    this.getRegionGroup(this.provinceIdConfig);
    try {
      this.tableColumn.find(item => item.prop === 'businessType').options = businessTypeOptions;
      this.filterArray.find(item => item.key === 'businessType').options = businessTypeOptions;
    } catch (e) {
      console.log("找不到对应表单项", e)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  min-height: inherit;

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
}
</style>
